import { HttpContext } from '@angular/common/http';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';
import { LoadingService } from '@delon/abc/loading';
import { LoadingType } from '@delon/abc/loading/loading.types';
import { XlsxService } from '@delon/abc/xlsx';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { finalize } from 'rxjs/operators';

import { Api } from '../../../shared/api/api';
import { ResponseCode } from '../../../shared/response.code';

@Component({
  selector: 'components-xlsx-import',
  template: `
    <div class="modal-header">
      <div class="modal-title">导入客户数据</div>
    </div>
    <input type="file" (change)="change($event)" multiple="false" class="ml-sm" />
    <p class="mt-sm" style="max-height:500px;overflow: hidden;text-overflow: ellipsis;"
      >总共 {{ list.Sheet0 ? list.Sheet0.length - 1 : list.Sheet1.length - 1 }} 条数据: {{ data | json }}</p
    >
    <div class="modal-footer">
      <button nz-button type="button" (click)="close()">关闭</button>
      <button nz-button type="submit" nzType="primary" (click)="save()" [disabled]="!data" [nzLoading]="http.loading">保存</button>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ComponentsXlsxImportComponent {
  data: any;
  status: any;
  list: any = {
    Sheet0: [],
    Sheet1: []
  };
  customer: any = {
    name: '',
    company_name: '',
    company_address: '',
    phone: '',
    business_scope: '',
    business_style: ''
  };
  customerList: any = [];
  constructor(
    private xlsx: XlsxService,
    private modal: NzModalRef,
    protected http: _HttpClient,
    private loadingSrv: LoadingService,
    private msgSrv: NzMessageService,
    private cdr: ChangeDetectorRef
  ) {}

  change(e: Event): void {
    const node = e.target as HTMLInputElement;
    this.xlsx.import(node.files![0]).then(res => {
      this.data = res;
      // @ts-ignore
      this.list = res;
      this.cdr.detectChanges();
    });
    node.value = '';
  }
  close() {
    this.modal.destroy();
  }
  show(type: LoadingType) {
    this.loadingSrv.open({ type });
  }
  save() {
    this.customerList = [];
    const customer = this.list.Sheet0 ? this.list.Sheet0 : this.list.Sheet1;
    for (let i = 1; i < customer.length; i++) {
      const customer1: any = {
        status: this.status,
        name: '',
        company_name: '',
        last_flow_up_record: '',
        aff_person: '',
        enter_pool_time: '',
        give_up_reason: '',
        notes: '',
        xs_source: '',
        phone: '',
        wxchat: '',
        six: '',
        industry: '',
        company_num: '',
        company_address: '',
        last_flow_up_record_status: '',
        create_name: '',
        creat_time: '',
        front_aff_person: '',
        last_modify_time: '',
        last_modify_name: '',
        last_flow_up_time: '',
        last_flow_up_name: localStorage.getItem('user_name'),
        allocate_time: '',
        customer_status: '',
        manager_name: '',
        contacts_name: '',
        business_scope: ''
      };
      customer1.name = customer[i][0];
      customer1.company_name = customer[i][1];
      customer1.last_flow_up_record = customer[i][2];
      customer1.aff_person = customer[i][3];
      customer1.enter_pool_time = customer[i][4];
      customer1.give_up_reason = customer[i][5];
      customer1.notes = customer[i][6];
      customer1.xs_source = customer[i][7];
      customer1.phone = customer[i][8];
      customer1.wxchat = customer[i][9];
      customer1.six = customer[i][10];
      customer1.industry = customer[i][11];
      customer1.company_num = customer[i][12];
      customer1.company_address = customer[i][13];
      customer1.last_flow_up_record_status = customer[i][14];
      customer1.create_name = customer[i][15];
      customer1.creat_time = customer[i][16];
      customer1.last_modify_time = customer[i][17];
      customer1.last_modify_name = customer[i][18];
      customer1.last_flow_up_time = customer[i][19];
      customer1.allocate_time = customer[i][21];
      customer1.customer_status = customer[i][22];
      customer1.manager_name = customer[i][23];
      customer1.contacts_name = customer[i][24];
      customer1.front_aff_person = customer[i][25];
      this.customerList.push(customer1);
    }
    console.log(this.customerList);
    this.add();
  }
  add() {
    this.show('spin');
    this.http
      .post(
        Api.BaseAddCustomerApi,
        this.customerList,
        {},
        {
          headers: {
            Authorization: 'Bearer dGVzdDp0ZXN0'
          },
          context: new HttpContext().set(ALLOW_ANONYMOUS, true)
        }
      )
      .pipe(
        finalize(() => {
          this.loadingSrv.close();
          this.cdr.detectChanges();
        })
      )
      .subscribe((res: any) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          this.loadingSrv.close();
          this.msgSrv.success('保存成功');
          this.modal.close(true);
        }
      });
  }
}
